<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class User extends MX_Controller {
    
    private $_data = array();
    function __construct(){
        parent::__construct();
        $this->load->model('user_model');        
        //$this->load->library('ion_auth');		
		$this->load->helper('url');
		// Load MongoDB library instead of native db driver if required
		$this->config->item('use_mongodb', 'ion_auth') ? $this->load->library('mongo_db') :	$this->load->database();
    }
    // index == login function
    function index(){ 
        
        if (!$this->ion_auth->logged_in())
		{
			//redirect them to the login page
			redirect('user/login', 'location');
		}
		elseif ($this->ion_auth->is_admin()) //remove this elseif if you want to enable this for non-admins
		{
			//redirect them to the home page because they must be an administrator to view this
			//return show_error('You must be an administrator to view this page.');
            redirect('admin', 'location');  
		}
		else
		{
			redirect('user/account/index', 'location');  
		}     
    }
    public function login(){
        if ($this->ion_auth->logged_in()){
            redirect('user/index', 'location');
        }
        //$this->template->add_js('assets/scripts/bootrap/tooltip.js');
        $this->template->add_js('assets/scripts/users/login.js');
        $data = array();
        $this->template->parse_view('content' , 'user/login', $data);
        $this->template->render(); 
    }    
    
    public function login_facebook(){
        if ($this->ion_auth->logged_in()){
            redirect('user/index', 'location');
            return ;
        }
        $this->load->library('facebook/facebook');       
        
        $facebook = new Facebook(array(
                    'appId' => OAUTH_FACEBOOK_APP_ID,
                    'secret' => OAUTH_FACEBOOK_CONSUMER_SECRET ,  
                    'cookie' => true,
                    'xfbml'     => true,
                    'oauth'      => true,
                ));

        $fb_user = $facebook->getUser(); 
    //var_dump($fb_user);
        if ($fb_user || $fb_user != 0) {  
            try {
                $user_profile = $facebook->api('/me');      
                $uid = tbnd_login_facebook_login_validate($user_profile); 
                if ($uid != null)
                    $uid = 'Facebook';
                $this->template->parse_view('content' , 'user/login_social/login_oauth_popup',array('user_oauth' => $user_profile));
                $this->template->render(); 
                //print theme('tbnd_login_oauth_popup', array('user_oauth' => $user_profile));
                $facebook->destroySession();	
            } catch (FacebookApiException $e) {
                $fb_user = null;
                //$facebook->destroySession();	
            }
        } 
        else{ 
        
            $loginUrl = $facebook->getLoginUrl(
                                        array(
                                            'display'   => 'popup',
                                            'scope' => 'email,read_stream, publish_stream,user_birthday, user_location, user_work_history, user_hometown, user_photos' , 
                                        )
                                );  
       header('Location: ' . $loginUrl , TRUE, $http_response_code);
        }
    }
    
    public function login_google(){
        if ($this->ion_auth->logged_in()){
            redirect('user/index', 'location');
            return ;
        }         
        require_once(APPPATH.'libraries/lightopenid/lightOpenID.php');
        $this->load->library('social_login'); 
        if (isset($_GET['openid_ext1_value_email'])) {
            $uid = $this->social_login->google_login_validate($_GET);
            if ($uid != null)
                $uid = 'Google';
            $this->template->parse_view('content' , 'user/login_social/login_oauth_popup',array('user_oauth' => NULL));
            $this->template->render(); 
        } else {        
            $openid = new LightOpenID(base_url());
            $openid->identity = 'https://www.google.com/accounts/o8/id';
            //setting call back url
            $openid->returnUrl = base_url() . 'user/login_google';
            //finding open id end point from google
            $endpoint = $openid->discover('https://www.google.com/accounts/o8/id');
            $fields =
                    '?openid.ns=' . urlencode('http://specs.openid.net/auth/2.0') .
                    '&openid.return_to=' . urlencode($openid->returnUrl) .
                    '&openid.claimed_id=' . urlencode('http://specs.openid.net/auth/2.0/identifier_select') .
                    '&openid.identity=' . urlencode('http://specs.openid.net/auth/2.0/identifier_select') .
                    '&openid.mode=' . urlencode('checkid_setup') .
                    '&openid.ns.ax=' . urlencode('http://openid.net/srv/ax/1.0') .
                    '&openid.ax.mode=' . urlencode('fetch_request') .
                    '&openid.ax.required=' . urlencode('email,firstname,lastname,dob,gender,fullname') .
                    '&openid.ax.type.firstname=' . urlencode('http://axschema.org/namePerson/first') .
                    '&openid.ax.type.lastname=' . urlencode('http://axschema.org/namePerson/last') .
                    '&openid.ax.type.fullname=' . urlencode('http://axschema.org/namePerson') .
                    '&openid.ax.type.dob=' . urlencode('http://axschema.org/birthDate') .
                    '&openid.ax.type.gender=' . urlencode('http://axschema.org/person/gender') .
                    '&openid.ax.type.email=' . urlencode('http://axschema.org/contact/email');            
            header('Location: ' . $endpoint . $fields , false);  
        }
    }
    
    public function login_yahoo(){        
        require_once(APPPATH.'libraries/OAuth/OAuth.php');
        require_once(APPPATH.'libraries/yahoo/OAuth.YahooOAuthApplication.php');
        
        $oauthapp = new YahooOAuthApplication(OAUTH_YAHOO_CONSUMER_KEY, OAUTH_YAHOO_CONSUMER_SECRET, OAUTH_YAHOO_APP_ID, OAUTH_YAHOO_DOMAIN); 


        if (isset($_GET['openid_mode']) && $_GET['openid_mode'] == 'id_res') {
            $request_token = new YahooOAuthRequestToken($_GET['openid_oauth_request_token'],'');
            $_SESSION['yahoo_oauth_request_token'] = $request_token->to_string();

            // exchange request token for access token
            $oauthapp->token = $oauthapp->getAccessToken($request_token);

            // store access token for later use
            $_SESSION['yahoo_oauth_access_token'] = $oauthapp->token->to_string();
        }
        if (isset($_GET['action'])) { 	 
            if($_GET['action'] == 'login') {
                header('Location: ' . $oauthapp->getOpenIDUrl($oauthapp->callback_url)); //go to Yahoo for authentification and authorization
                exit;
            }

        } else {	 
            if (isset($_SESSION['yahoo_oauth_access_token'])) {
                // if session is still present ( not expired),then restore access token from session
                $oauthapp->token = YahooOAuthAccessToken::from_string($_SESSION['yahoo_oauth_access_token']);
            }
        }

        if (isset($_SESSION['yahoo_oauth_request_token'])) {
            $profile = $oauthapp->getProfile(); // fetch profile information
            if($profile){ 
                $profile = $profile->profile;  
                $uid = $this->social_login->yahoo_login_validate($profile);
                if ($uid != null)
                    $uid = 'Yhaoo';
                $this->template->parse_view('content' , 'user/login_social/login_oauth_popup',array('user_oauth' => NULL));
                $this->template->render(); 
            }
            else{
                return NULL;
            }
        }
    }
            
    public function register(){
        $this->template->add_js('assets/scripts/users/login.js');
        $data = array();
        $this->template->parse_view('content' , 'users/signup', $data);
        $this->template->render();        
    }
    
    public function create(){ 
        if($_SERVER['REQUEST_METHOD'] == 'POST'){
            $name_error = array();
            $json = array();
            $security_code = trim($this->input->post('verifycode'));
            $to_check = md5($security_code);                     
            if($this->user_model->checkHaveEmail($this->input->post('email'))){
                array_push($name_error, array('field' => 'email' , 'ngshow' => 'isTaken'));
                $json['success'] = FALSE;
                $json['message'] = 'Đăng kí không thành công.';
                $json['name_error'] = $name_error; 
            }            
            elseif($to_check != $this->session->userdata('security_code')){
                array_push($name_error, array('field' => 'verifycode' , 'ngshow' => 'required'));
                $json['success'] = FALSE;
                $json['message'] = 'Đăng kí không thành công.';
                $json['name_error'] = $name_error; 
            }  
            else{ 
                $username = strtolower($this->input->post('email'));
                $email    = strtolower($this->input->post('email'));
                $password = $this->input->post('password');

                $additional_data = array(
                    'avatar' => 0 ,
                    'full_name'  => $this->input->post('name'),                  
                    'phone'      => '0909090909',
                );
                if($this->ion_auth->register($username, $password, $email, $additional_data)){                
                    $json['success'] = TRUE;
                    $json['message'] = 'Đăng kí không thành công.';
                    $json['name_error'] = $name_error; 
                    
                    ///send mail to member
                    $this->load->library('send_mail');                
                    $user = new stdClass();
                    $user->full_name = $this->input->post('name');  
                    $user->email = $email;
                    $user->password = $password;
                    $data_email = array(
                        'data' => $user ,
                        'subject' => 'Thông tin tài khoản tại myprints.vn',
                        'mail_to' => $user->email ,
                        'view' => 'signup_social' ,                    
                    );
                    $this->send_mail->send_mail($data_email);
                    //end send mail
                }
                else{
                    $json['success'] = FALSE;
                    $json['message'] = 'Đăng kí không thành công.';
                    $json['name_error'] = $name_error; 
                }
            }
           // elseif($this->)
            echo json_encode($json);  
            return; 
        }
        else{
            
        }
    }
    
    public function check_login(){
        $this->load->library('encrypt');       
        $name_error = array();
        $json = array();         
        
        $remember = (bool) $this->input->post('remember');
        $check_login = $this->ion_auth->login($this->input->post('email'), $this->input->post('password'), $remember);
        if ($check_login)
        {             
            //if the login is successful
            //redirect them back to the home page
            $this->session->set_flashdata('message', $this->ion_auth->messages());            
            //redirect('', 'location');
        }
        else
        {       
            array_push($name_error, array('field' => 'password' , 'ngshow' => 'invalid'));
            $json['message'] = 'Đăng nhập thất bại. <br /> Sai email hoặc password.';
            //if the login was un-successful
            //redirect them back to the login page
            //$this->session->set_flashdata('message', $this->ion_auth->errors());
            //redirect('auth/login', 'refresh'); //use redirects instead of loading views for compatibility with MY_Controller libraries
        }           
        $json['success'] = $check_login;
        $json['name_error'] = $name_error; 
        echo json_encode($json);  
        return ;
    }
    
    public function check_email(){
        $email= $this->input->post('email');
        $json['isTaken'] = $this->user_model->checkHaveEmail($this->input->post('email'));
        echo json_encode( $json );
        return ;
    }
    
    public function account( $param ){
        if (!$this->ion_auth->logged_in()){
            redirect('/', 'location');
            return ;
        }
        $data = array();
        $data['message'] = '';
         
        switch( $param ){
            case 'index': 
                if(isset($_POST) && !empty($_POST)){
                    $data_update = array(
                                        'full_name' => $this->input->post('full_name'),
                                        'email'  => $this->input->post('email'),				
                                        'phone'      => $this->input->post('phone'),
                                );
                    $this->ion_auth->update($this->ion_auth->get_user_id() , $data_update);
                    $this->session->set_flashdata('message', "Lưu thành công");
                    $data['message'] = "Lưu thành công";
                }       
                $data['title'] = "Quản lý tài khoản của bạn";
                $user = $this->ion_auth->user()->row_array();
                $data['data']  = $user; 
                break;
            case 'edit':
                if(isset($_POST) && !empty($_POST)){ 
                    if($this->input->post('day_birth') && $this->input->post('month_birth') && $this->input->post('year_birth')){
                        $birth_date = strtotime($this->input->post('year_birth') . '-' . $this->input->post('month_birth') . '-' . $this->input->post('day_birth'));
                    }
                    else{
                        $birth_date = 0;
                    }                  
                    $data_update = array(
                                        'full_name' => $this->input->post('full_name'),
                                        'email'     => $this->input->post('email'),				
                                        'phone'     => $this->input->post('phone'),
                                        'sex'       => $this->input->post('sex'),
                                        'birthday'  => $birth_date
                                );
                    $this->ion_auth->update($this->ion_auth->get_user_id() , $data_update);
                    $this->session->set_flashdata('message', "Lưu thành công");
                    $data['message'] = "Lưu thành công";
                }       
                $data['title'] = "Chỉnh sửa tài khoản";
                $user = $this->ion_auth->user()->row_array(); 
                $data['data']  = $user;
                break;
            case 'address':
                $uid = $this->ion_auth->get_user_id();
                if(isset($_POST) && !empty($_POST)){             
                    $data_update = array(
                        'uid' => $uid,
                        'full_name'  => $this->input->post('full_name'),				
                        'fone'      => $this->input->post('fone'),
                        'address'  => $this->input->post('address'),				
                        'city'      => $this->input->post('city'),
                        'district'      => $this->input->post('district'),
                    );
                    $check_address_book = $this->user_model->check_address_book( $uid );
                    if($check_address_book){//if have address book is update                        
                        $this->user_model->update_address_book( $uid , $data_update);
                    }
                    else{
                        $this->user_model->insert_address_book( $data_update );
                    }                   
                    $data['message'] = "Lưu thành công";
                }       
                $this->load->model('library/library_model');              
                $data['data']['address']  = $this->user_model->get_address_book_by_uid( $uid ); 
                $data['data']['city'] = $this->library_model->get_all_city();    
                $data['data']['district'] = $this->library_model->get_district_by_city( @$data['data']['address']['city'] ); //die(print_r($data));    
                $data['title'] = "Sổ địa chỉ";                
                break;      
            case 'changepassword':
                $uid = $this->ion_auth->get_user_id();
                if(isset($_POST) && !empty($_POST)){   
                    $user = $this->ion_auth->user()->row();
                    $identity = $this->session->userdata($this->config->item('identity', 'ion_auth'));

                    $change = $this->ion_auth->change_password($identity, $this->input->post('password_old'), $this->input->post('password_new'));

                    if($change)
                    { 
                        //if the password was successfully changed
                        $this->session->set_flashdata('message', $this->ion_auth->messages());
                        //$this->logout();
                        $data['message'] = "Lưu thành công";
                        $data['success'] = true;
                    }
                    else
                    { 
                        $this->session->set_flashdata('message', $this->ion_auth->errors());
                        //redirect('user/account/changepassword', 'refresh');
                        $data['message'] = 'Lưu không thành công.<br />Mật khẩu hiện tại không chính xác.';
                        $data['success'] = false;
                    }                    
                    
                }       
                $data['data'] = array();
                $data['title'] = "Thay đổi mật khẩu";        
                break;
            default :
                
                break;
           
        }
        $this->template->add_css('assets/css/users/account.css');
        $this->template->add_js('assets/scripts/users/account.js');
       
        $data['param'] = $param;   
        
        $this->template->parse_view('content' , 'user/account', $data);
        $this->template->render();    
    }
    
    public function check_password(){  
        
        
    }
    //forgot password
    public function forgotpassword(){
        $this->template->add_js('assets/scripts/users/login.js');
        $data['message'] = '';
        if(isset($_POST) && !empty($_POST)){
            $email = $this->input->post('email');
            if(!$this->ion_auth->email_check($email)){
                $data['message'] = 'Email này không tồn tại trong hệ thống của myprints.vn, vui lòng kiểm tra lại.';
                $data['success'] = false;
            }
            else{
                if($this->ion_auth->forgotten_password( $email )){
                    $data['message'] = 'Gửi thành công.';
                    $data['success'] = true;
                    $user = $this->user_model->get_user_by_array($email , array('email' , 'full_name' , 'forgotten_password_code' , 'forgotten_password_time') , 'email');
                    ///send mail to member                    
                    $this->load->library('send_mail');   
                    $data_email = array(
                        'data' => $user ,
                        'subject' => 'myprints.vn - Xác nhận phục hồi mật khẩu',
                        'mail_to' => $email ,
                        'view' => 'forgotten_password' ,                    
                    );
                    $this->send_mail->send_mail($data_email);
                    //end send mail             
                }
            }
        }        
        $this->template->parse_view('content' , 'user/forgotpassword', $data);
        $this->template->render();    
    }
    
    public function restorepassword($key , $code){       
        if (!$code)
		{
			show_404();
		}
        $this->load->library('form_validation');
		$this->load->helper('url');
        $user = $this->ion_auth->forgotten_password_check($code);       
        $this->template->add_js('assets/scripts/users/login.js');
        $data = array();
        $data['message'] = '';       
		
        if ($user){
            if(isset($_POST) && !empty($_POST)){
                if ($this->_valid_csrf_nonce() === FALSE || $user->id != $this->input->post('user_id'))
                {                    
                    //something fishy might be up
                    $this->ion_auth->clear_forgotten_password_code($code);

                    show_error($this->lang->line('error_csrf'));

                }
                else
                {                   
                    // finally change the password
                    $identity = $user->{$this->config->item('identity', 'ion_auth')};

                    $change = $this->ion_auth->reset_password($identity, $this->input->post('password'));

                    if($change)
                    {
                        //if the password was successfully changed
                        $this->session->set_flashdata('message', $this->ion_auth->messages());
                        $this->logout();
                    }
                    else
                    {
                        $this->session->set_flashdata('message', $this->ion_auth->errors());
                        redirect('auth/reset_password/' . $code, 'refresh');
                    }
                }
            }
			//if the code is valid then display the password reset form
            $data['user_id'] = $user->id;
            $data['csrf'] = $this->_get_csrf_nonce();
            $data['code'] = $code;		
            //render				
            $this->template->parse_view('content' , 'user/reset_password', $data);
            $this->template->render();    
		}
		else{
			//if the code is invalid then send them back to the forgot password page
			$this->session->set_flashdata('message', $this->ion_auth->errors());
			redirect("user/forgotpassword", 'refresh');
		}
    }
    
    function _get_csrf_nonce()
	{
		$this->load->helper('string');
		$key   = random_string('alnum', 8);
		$value = random_string('alnum', 20);
		$this->session->set_flashdata('csrfkey', $key);
		$this->session->set_flashdata('csrfvalue', $value);

		return array($key => $value);
	}

	function _valid_csrf_nonce()
	{
		if ($this->input->post($this->session->flashdata('csrfkey')) !== FALSE &&
			$this->input->post($this->session->flashdata('csrfkey')) == $this->session->flashdata('csrfvalue'))
		{
			return TRUE;
		}
		else
		{
			return FALSE;
		}
	}
    
    public function logout(){  
        //$this->data['title'] = "Logout";

        //log the user out
        $logout = $this->ion_auth->logout();

		//redirect them to the login page
	$this->session->set_flashdata('message', $this->ion_auth->messages());		
        redirect('', 'location');
        return;  
    }  
   
    
    function useIsLogin(){                  
        $session_user = $this->session->userdata('user'); 
        $cookie_user = $this->input->cookie('remember_login');        
        if($session_user['logged_in'] == true){
            return true;
        }
        elseif($session_user['logged_in'] == false &&  $cookie_user['logged_in'] == true){
            $this->session->set_userdata('user', array('uid' => $cookie_user['uid'] , 'logged_in' => $cookie_user['logged_in']));
            return true;
        }
        else{
            return false;
        }      
        return false;
    }
    
    
    /**
     * 
     * section call ajax
     * 
     */
    
/* ==================================

    END CLASS
    
===================================== */
}